import axios from 'axios';
import { Loading, Toast } from 'vant';
import Vue from 'vue';
Vue.use(Loading);
Vue.use(Toast);

export function fetch(url, params = {}, method = 'POST', { withMask = true, ...config } = {}) {
    if (!url) {
        throw new Error('interface path not found');
    }

    let isGet = method.toUpperCase() === 'GET',
        toast = null;

    if (withMask) {
        toast = Toast.loading({
            duration: 0,
            mask: true,
            message: '加载中...'
        });
    }

    return new Promise((resolve, reject) => {
        axios({
            url: url,
            method,
            params: isGet ? params : '',
            data: isGet ? '' : params,
            ...config
        }).then(rep => {
            toast && toast.clear();
            resolve(rep);
        }, err => {
            toast && toast.clear();
            reject(err);
        });
    });
}

export function fetchAll(...promises) {
    let toast = Toast.loading({
        duration: 0,
        mask: true,
        message: '加载中...'
    });

    return Promise.all(promises).then(rep => {
        toast.clear();
        return rep;
    }, err => {
        toast.clear();
        return err;
    });
}
